﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PrVyd.Zakladni_tridy
{
    class PaymentManager
    {
        public List<Payment> Payments
        {
            get { return FindAllPayments(); }
        }

        public bool CreatePayment(Payment payment)
        {
            try
            {
                XDocument doc = DatabaseManager.LoadDBX();
                doc.Descendants("payments").First().Add(DBUtils.Payment2Element(payment));
                DatabaseManager.SaveDB(doc);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool UpdatePayment(Payment payment)
        {
            XDocument doc = DatabaseManager.LoadDBX();
            try
            {
                foreach (XElement item in doc.Descendants("payment"))
                    if (item.Element("number").Value.Equals(payment.Number.ToString()))
                    {
                        item.Parent.Add(DBUtils.Payment2Element(payment));
                        item.Remove();
                        DatabaseManager.SaveDB(doc);
                        return true;
                    }
            }
            catch (Exception)
            {
                return false;
            }
            return false; //nemelo by nastat
        }

        public bool DeletePayment(long id)
        {
            XDocument doc = DatabaseManager.LoadDBX();
            try
            {
                foreach (XElement item in doc.Descendants("payment"))
                    if (item.Element("number").Value.Equals(id.ToString()))
                    {
                        item.Remove();
                        DatabaseManager.SaveDB(doc);
                        return true;
                    }
            }
            catch (Exception)
            {
                return false;
            }

            return false;
        }

        private List<Payment> FindAllPayments()
        {
            List<Payment> payments = new List<Payment>();
            XDocument doc = DatabaseManager.LoadDBX();
            foreach (XElement payment in doc.Descendants("payment"))
                payments.Add(DBUtils.Element2Payment(payment));

            return payments;
        }
    }
}
